package network.reflection.rmi;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SimpleServer {

	private Map remoteObjects = new HashMap();	//缓存远程对象用的
	
	public void register(String className, Object remoteObject){
		remoteObjects.put(className, remoteObject);
	}
	
	public void service() throws Exception{
		ServerSocket server = new ServerSocket(8080);
		System.out.println("服务器启动成功");
		while(true){
			Socket client = server.accept();
			InputStream is = client.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			
			OutputStream os = client.getOutputStream();
			ObjectOutputStream oos = new  ObjectOutputStream(os);
			
			Call call = (Call) ois.readObject();
			System.out.println(call);
			
			call = invoke(call);
			oos.writeObject(call);
			
			ois.close();
			oos.close();
			client.close();
		}
		
	}
	
	public Call invoke(Call call){
		Object result = null;
		
		try{
			String className = call.getClassName();
			String methodName = call.getMethodName();
			Object[] params = call.getParams();
			Class[] paramsType = call.getParamsType();
					
			Class classType = Class.forName(className);
			Method method = classType.getMethod(methodName, paramsType);
			
			Object remoteObject = remoteObjects.get(className);
			if(remoteObject == null){
				throw new ClassNotFoundException(className + "远程对象不存在");
			}else{
				result = method.invoke(remoteObject, params);
			}
			
			
		}catch(ClassNotFoundException e1){
			result =e1;
		}catch(NoSuchMethodException e2){
			result = e2;
		}catch(InvocationTargetException e3){
			result = e3;
		}catch(IllegalAccessException e4){
			result = e4;
		}
		
		call.setResult(result);
		return call;
	}
	
	
	public static void main(String[] args) throws Exception{
		SimpleServer server = new SimpleServer();
		server.register("network.reflection.rmi.HelloService", new HelloServiceImpl());
		server.service();	
	}
}
